//
//  PhotoViewController.m
//  myCar
//
//  Created by 王子洁 on 14/10/29.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "PhotoViewController.h"
#import "UIImageView+WebCache.h"
#import "PhotoTableViewCell.h"
#import "MJRefresh.h"
#import "AlbumViewController.h"
#import "WebColor.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"

@interface PhotoViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>

@property (nonatomic, retain)NSMutableArray *groups;

@property (nonatomic, retain)NSMutableArray *cellCount;

@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, assign)int number;

@end

@implementation PhotoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.groups = [NSMutableArray array];
        self.cellCount = [NSMutableArray array];
        self.number = 0;
    }
    return self;
}

- (void)dealloc
{
    [_groups release];
    [_cellCount release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    //self.view.backgroundColor = [UIColor yellowColor];
    self.navigationController.navigationBar.tintColor = [WebColor white];
    
    // 初始化tableView
    [self initTableView];
    [self setupRefresh];
    [self setNet];
    
    
}

- (void)setNet
{
    MBProgressHUD *hub = [[MBProgressHUD alloc] init];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [hub show:YES];
    [self.view addSubview:hub];
    NSString *str = @"http://agent1.pconline.com.cn:8941/pcautophoto/iphone_cate_json.jsp?id=89";
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"ress %@", [responseObject class]);
        NSArray *arr = [responseObject valueForKey:@"groups"];
        for (NSDictionary *dic in arr) {
            Information *info = [[Information alloc] init];
            info.title = [dic valueForKey:@"name"];
            info.url = [dic valueForKey:@"url"];
            info.image = [dic valueForKey:@"cover"];
            NSString *str = [[dic valueForKey:@"photoCount"] description];
            info.count = [NSString stringWithFormat:@"%@张", str];
            info.number = [dic valueForKey:@"id"];
            [self.groups addObject:info];
            [info release];
        }
        for (int i = 0 + 50 * self.number; i < 50 + 50 * self.number; i++) {
            Information *info = [self.groups objectAtIndex:i];
            [self.cellCount addObject:info];
        }
        [self.tableView reloadData];
        [hub removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
        imageView.image = [UIImage imageNamed:@"poNet.jpg"];
        self.tableView.backgroundView = imageView;
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
        [imageView release];
    }];
}

- (void)initTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
    [_tableView release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.cellCount.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    PhotoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[PhotoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:str]autorelease];
    }
    Information *info = [self.groups objectAtIndex:indexPath.row];
    [cell.photoImage setImageWithURL:[NSURL URLWithString:info.image]];
    cell.countLabel.text = info.count;
    cell.titleLabel.text = info.title;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 180;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AlbumViewController *albumVC = [[AlbumViewController alloc] init];
    Information * info = [self.groups objectAtIndex:indexPath.row];
    albumVC.info = info;
    CATransition *animation = [CATransition animation];
    
    [animation setDuration:0.3];
    
    [animation setType: kCATransitionMoveIn];
    
    [animation setSubtype: kCATransitionFromTop];
    
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];

    [self.navigationController.view.layer addAnimation:animation forKey:nil];
    [self.navigationController pushViewController:albumVC animated:NO];
    [albumVC release];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark 刷新方法
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
//    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
//    [self.tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.tableView footerEndRefreshing];
    //
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
//    self.tableView.headerPullToRefreshText = @"下拉以上弦...";
//    self.tableView.headerReleaseToRefreshText = @"松开即可上弦...";
//    self.tableView.headerRefreshingText = @"上弦中...";
    
    self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.tableView.footerRefreshingText = @"加载中";
    
    //self.countx = 2;
}
#pragma mark 开始进入刷新状态
//- (void)headerRereshing
//{
//    // 2.2秒后刷新表格UI
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        
//        // 刷新表格
//        [self.tableView reloadData];
//        
//        [_tableView reloadData];
//        
//        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
//        [self.tableView headerEndRefreshing];
//    });
//}

- (void)footerRereshing
{
    //_dataSource = [[NSMutableArray alloc]init];
    
    self.number += 1;
    if (50 + 50 * self.number <= self.groups.count) {
    for (int i = 0 + 50 * self.number; i < 50 + 50 * self.number; i++) {
        Information *info = [self.groups objectAtIndex:i];
        [self.cellCount addObject:info];
    }

    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView footerEndRefreshing];
        //_countx += 1;
    });
    }
}

#pragma mark -
#pragma mark cell将要出现时显示动画
- (void)tableView:(UITableView *)tableView willDisplayCell:(PhotoTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.frame = CGRectMake(320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    
    [UIView animateWithDuration:0.5 animations:^{
        cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
        
    }];

    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
